package com.whfc.common.util;

import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * http工具类
 */
public class HttpUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static final String UTF8 = "utf-8";

    private static final String HTTPS_REQUEST_START = "https://";

    /**
     * 默认连接 超时时间 单位 毫秒
     */
    private static final Integer DEFAULT_CONNECT_TIME = 60 * 1000;

    /**
     * 默认socket 超时时间 单位 毫秒
     */
    private static final Integer DEFAULT_SOCKET_TIME = 60 * 1000;

    /**
     * GET请求
     *
     * @param url 请求地址
     * @return 响应结果
     */
    public static String doGet(String url) throws BizException {
        return doGet(url, null, null);
    }

    /**
     * GET请求
     *
     * @param url
     * @param headers
     * @return
     * @throws BizException
     */
    public static String doGet(String url, Map<String, String> headers) throws BizException {
        return doGet(url, headers, null);
    }

    /**
     * 发送GET请求（带超时参数的版本）
     * 
     * @param url            请求地址
     * @param params         请求参数
     * @param headers        请求头
     * @param connectTimeout 连接超时时间
     * @param readTimeout    读取超时时间
     * @return 响应结果
     * @throws BizException 业务异常
     */
    public static String doGet(String url, Map<String, String> params, Map<String, String> headers,
            Integer connectTimeout, Integer readTimeout) throws BizException {
        String result = null;
        try {
            // 1. 根据URL创建适当的HttpClient（HTTP或HTTPS）
            HttpClient httpClient = wrapClient(url);

            // 2. 构建完整的请求URL（包含查询参数）
            HttpGet httpGet = new HttpGet(buildUrl(url, params));

            // 3. 设置超时配置
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(connectTimeout == null ? DEFAULT_CONNECT_TIME : connectTimeout)
                    .setSocketTimeout(readTimeout == null ? DEFAULT_SOCKET_TIME : readTimeout)
                    .build();
            httpGet.setConfig(config);

            // 4. 设置请求头
            if (headers != null && headers.entrySet().size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }

            // 5. 执行请求
            HttpResponse response = httpClient.execute(httpGet);

            // 6. 处理响应
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, UTF8);
                }
            }
        } catch (ConnectException ex) {
            // 7. 连接超时异常处理
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            // 8. 其他异常处理
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * 发送GET请求
     *
     * @param url     请求地址
     * @param headers 请求头
     * @param params  请求参数
     * @return 响应结果
     */
    public static String doGet(String url, Map<String, String> headers, Map<String, String> params)
            throws BizException {
        String result = null;
        try {
            HttpClient httpClient = wrapClient(url);
            HttpGet httpGet = new HttpGet(buildUrl(url, params));

            // 自定义header
            if (headers != null && headers.entrySet().size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }

            HttpResponse response = httpClient.execute(httpGet);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, UTF8);
                }
            }
        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * 发送post请求
     *
     * @param url  请求地址
     * @param body 内容(JSON格式)
     * @return 响应结果
     */
    public static String doPost(String url, String body) throws BizException {
        return doPost(url, body, null);
    }

    /**
     * 发送Post请求
     *
     * @param url     请求地址
     * @param body    json数据
     * @param headers 自定义请求头
     * @return 响应结果
     */
    public static String doPost(String url, String body, Map<String, String> headers) throws BizException {
        return doPost(url, body, headers, null, null);
    }

    /**
     * 发送Post请求
     *
     * @param url            地址
     * @param body           json数据
     * @param headers        自定义请求头
     * @param socketTimeout  socket超时
     * @param connectTimeout 连接超时
     * @return 响应结果
     */
    public static String doPost(String url, String body, Map<String, String> headers, Integer socketTimeout,
            Integer connectTimeout) throws BizException {
        String result = null;
        try {
            HttpClient httpClient = wrapClient(url);
            HttpPost httpPost = new HttpPost(url);
            // 超时
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(connectTimeout == null ? DEFAULT_CONNECT_TIME : connectTimeout)
                    .setSocketTimeout(socketTimeout == null ? DEFAULT_SOCKET_TIME : socketTimeout)
                    .build();
            httpPost.setConfig(config);

            // 自定义header
            httpPost.addHeader("Content-Type", "application/json");
            if (headers != null && headers.entrySet().size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }

            // body
            StringEntity se = new StringEntity(body, ContentType.APPLICATION_JSON);
            httpPost.setEntity(se);

            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, UTF8);
                }
            }
        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * 发送post请求
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 响应结果
     */
    public static String doPost(String url, Map<String, String> params) throws BizException {
        return doPost(url, params, null);
    }

    /**
     * 发送POST请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @param headers 请求头
     * @return 响应结果
     * @throws BizException 业务异常
     */
    public static String doPost(String url, Map<String, String> params, Map<String, String> headers)
            throws BizException {
        return doPost(url, params, headers, null, null);
    }

    /**
     * 发送post请求
     *
     * @param url            请求地址
     * @param params         请求参数
     * @param headers        请求头
     * @param socketTimeout  socket超时
     * @param connectTimeout 连接超时
     * @return 响应结果
     * @throws BizException 业务异常
     */
    public static String doPost(String url, Map<String, String> params, Map<String, String> headers,
            Integer socketTimeout, Integer connectTimeout) throws BizException {
        String result = "";
        try {
            HttpClient httpClient = wrapClient(url);
            HttpPost httpPost = new HttpPost(url);
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(connectTimeout == null ? DEFAULT_CONNECT_TIME : connectTimeout)
                    .setSocketTimeout(socketTimeout == null ? DEFAULT_SOCKET_TIME : socketTimeout)
                    .build();
            httpPost.setConfig(config);
            // 自定义header
            if (headers != null && headers.entrySet().size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // body
            if (params != null) {
                List<NameValuePair> nameValuePairList = new ArrayList<>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, UTF8);
                httpPost.setEntity(formEntity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, UTF8);
                }
            }

        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * 删除请求
     *
     * @param url
     * @return
     * @throws BizException
     */
    public static String doDelete(String url) throws BizException {
        String result = "";
        try {
            HttpClient httpClient = wrapClient(url);
            HttpDelete request = new HttpDelete(url);
            HttpResponse response = httpClient.execute(request);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }
        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * 删除请求
     *
     * @param host   请求地址
     * @param path   请求路径
     * @param params 请求参数
     * @return 响应结果
     */
    public static String doDelete(String host, String path, Map<String, String> params) {
        String result = "";
        try {
            HttpClient httpClient = wrapClient(host);
            HttpDelete request = new HttpDelete(buildUrl(host, path, params));
            HttpResponse response = httpClient.execute(request);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }
        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * 删除请求
     *
     * @param host   请求地址
     * @param path   请求路径
     * @param params 请求参数
     * @return 响应结果
     */
    public static String doDelete(String host, String path, Map<String, String> params, Map<String, String> headers) {
        String result = "";
        try {
            HttpClient httpClient = wrapClient(host);
            HttpDelete request = new HttpDelete(buildUrl(host, path, params));
            // 自定义header
            if (headers != null && headers.entrySet().size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            }
            HttpResponse response = httpClient.execute(request);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }
        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * put请求
     *
     * @param url
     * @param headers
     * @return
     */
    public static String doPut(String url, Map<String, String> headers) {
        return doPut(url, headers, "");
    }

    /**
     * put请求
     *
     * @param url
     * @param headers
     * @param body
     * @return
     */
    public static String doPut(String url, Map<String, String> headers, String body) {
        String result = null;
        try {
            HttpClient httpClient = wrapClient(url);
            HttpPut httpPut = new HttpPut(buildUrl(url, null));

            // 自定义header
            if (headers != null && headers.entrySet().size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPut.addHeader(entry.getKey(), entry.getValue());
                }
            }

            // body
            StringEntity se = new StringEntity(body, ContentType.APPLICATION_JSON);
            httpPut.setEntity(se);

            HttpResponse response = httpClient.execute(httpPut);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, UTF8);
                }
            }
        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * PUT请求
     *
     * @param host   请求地址
     * @param path   请求路径
     * @param params 请求参数
     * @param body   请求内容
     * @return 响应结果
     */
    public static String doPut(String host, String path, Map<String, String> params, byte[] body) throws BizException {
        String result = "";
        try {
            HttpClient httpClient = wrapClient(host);
            HttpPut request = new HttpPut(buildUrl(host, path, params));

            if (body != null) {
                request.setEntity(new ByteArrayEntity(body));
            }
            HttpResponse response = httpClient.execute(request);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }

        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * PUT请求
     *
     * @param host    请求地址
     * @param path    请求路径
     * @param params  请求参数
     * @param headers 请求内容
     * @return 响应结果
     */
    public static String doPut(String host, String path, Map<String, String> params, Map<String, String> headers)
            throws BizException {
        String result = "";
        try {
            HttpClient httpClient = wrapClient(host);
            HttpPut request = new HttpPut(buildUrl(host, path, params));
            // 自定义header
            if (headers != null && headers.entrySet().size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    request.addHeader(entry.getKey(), entry.getValue());
                }
            }
            HttpResponse response = httpClient.execute(request);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }

        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * 上传文件的HTTP请求
     *
     * @param url      url
     * @param jsonKey  json key
     * @param jsonBody 对象json字符串
     * @param files    文件集合Map<文件名，文件数组>
     * @return 响应结果
     */
    public static String uploadFile(String url, String jsonKey, String jsonBody, Map<String, File[]> files)
            throws BizException {
        HttpClient httpClient;
        HttpPost httpPost;
        String result = "";
        try {
            httpClient = wrapClient(url);
            httpPost = new HttpPost(url);
            RequestConfig config = RequestConfig.custom()
                    .setConnectionRequestTimeout(DEFAULT_CONNECT_TIME)
                    .setConnectTimeout(DEFAULT_CONNECT_TIME)
                    .setSocketTimeout(DEFAULT_SOCKET_TIME)
                    .build();
            httpPost.setConfig(config);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setCharset(StandardCharsets.UTF_8);
            if (StringUtils.isNotEmpty(jsonBody)) {
                builder.addTextBody(jsonKey, jsonBody, ContentType.create("text/plain", StandardCharsets.UTF_8));
            }
            if (files != null && !files.isEmpty()) {
                for (Map.Entry<String, File[]> entry : files.entrySet()) {
                    String fileName = entry.getKey();
                    File[] fileList = entry.getValue();
                    for (File file : fileList) {
                        builder.addBinaryBody(fileName, file);
                    }
                }
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }
        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * 上传文件的HTTP请求
     *
     * @param url    url
     * @param params form表单参数
     * @param files  文件集合Map<文件名，文件数组>
     * @return 响应结果
     */
    public static String uploadFile(String url, Map<String, String> params, Map<String, File> files)
            throws BizException {
        HttpClient httpClient;
        HttpPost httpPost;
        String result = "";
        try {
            httpClient = wrapClient(url);
            httpPost = new HttpPost(url);
            RequestConfig config = RequestConfig.custom()
                    .setConnectionRequestTimeout(DEFAULT_CONNECT_TIME)
                    .setConnectTimeout(DEFAULT_CONNECT_TIME)
                    .setSocketTimeout(DEFAULT_SOCKET_TIME)
                    .build();
            httpPost.setConfig(config);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setCharset(StandardCharsets.UTF_8);
            // body
            if (params != null) {
                List<NameValuePair> nameValuePairList = new ArrayList<>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, UTF8);
                httpPost.setEntity(formEntity);
            }
            // file
            if (files != null && !files.isEmpty()) {
                for (Map.Entry<String, File> entry : files.entrySet()) {
                    String fileName = entry.getKey();
                    File file = entry.getValue();
                    builder.addBinaryBody(fileName, file);
                }
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }
        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return result;
    }

    /**
     * 下载文件
     *
     * @param url
     * @return
     */
    public static InputStream downLoad(String url) {
        try {
            HttpClient httpClient = wrapClient(url);
            HttpGet httpGet = new HttpGet(buildUrl(url, null));

            HttpResponse response = httpClient.execute(httpGet);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    return resEntity.getContent();
                }
            }
        } catch (ConnectException ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_TIMEOUT.getCode(), ResultEnum.NETWORK_TIMEOUT.getMessage());
        } catch (Exception ex) {
            logger.error("", ex);
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
        return null;
    }

    /**
     * 构建URL
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 拼接后的地址
     */
    public static String buildUrl(String url, Map<String, String> params) {

        if (params == null || params.size() == 0) {
            return url;
        }

        StringBuilder queryStr = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (queryStr.length() > 0) {
                queryStr.append("&");
            }
            String query = String.format("%s=%s", entry.getKey(), entry.getValue());
            queryStr.append(query);
        }

        StringBuilder urlStr = new StringBuilder(url);
        if (url.lastIndexOf('?') == -1) {
            urlStr.append('?').append(queryStr.toString());
        } else {
            urlStr.append('&').append(queryStr.toString());
        }

        return urlStr.toString();
    }

    /**
     * 构建URL
     *
     * @param host   请求地址
     * @param path   请求路径
     * @param params 参数
     * @return 拼接地址
     */
    public static String buildUrl(String host, String path, Map<String, String> params) {
        String result = "";
        try {
            StringBuilder sbUrl = new StringBuilder();
            sbUrl.append(host);
            if (!StringUtils.isBlank(path)) {
                sbUrl.append(path);
            }
            if (null != params) {
                StringBuilder sbQuery = new StringBuilder();
                for (Map.Entry<String, String> query : params.entrySet()) {
                    if (0 < sbQuery.length()) {
                        sbQuery.append("&");
                    }
                    if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                        sbQuery.append(query.getValue());
                    }
                    if (!StringUtils.isBlank(query.getKey())) {
                        sbQuery.append(query.getKey());
                        if (!StringUtils.isBlank(query.getValue())) {
                            sbQuery.append("=");
                            sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                        }
                    }
                }
                if (0 < sbQuery.length()) {
                    sbUrl.append("?").append(sbQuery);
                }
            }
            result = sbUrl.toString();

        } catch (Exception e) {
            logger.error("", e);
        }

        return result;
    }

    /**
     * 包装 HttpClient
     *
     * @param host 请求地址
     * @return HttpClient
     */
    public static HttpClient wrapClient(String host) {
        HttpClient httpClient = HttpClients.createDefault();
        if (host.startsWith(HTTPS_REQUEST_START)) {
            return getHttpClient();
        }
        return httpClient;
    }

    /**
     * 忽略SSL证书认证
     *
     * @return HttpClient
     * @throws BizException 业务异常
     */
    public static CloseableHttpClient getHttpClient() throws BizException {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } }, new SecureRandom());
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
            return HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build();
        } catch (Exception e) {
            logger.warn("create closeable http client failed!");
            throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), ResultEnum.NETWORK_ERROR.getMessage());
        }
    }

}